
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <unistd.h>

#include "ohos_init.h"
#include "cmsis_os2.h"
#include "wifiiot_i2c.h"
#include "wifiiot_gpio.h"
#include "wifiiot_gpio_ex.h"
#include "wifiiot_pwm.h"
#include "wifiiot_adc.h"
#include "wifiiot_errno.h"

#include "aht20.h"
#include "led.h"
#include "beep.h"


#define GAS_SENSOR_CHAN_NAME WIFI_IOT_ADC_CHANNEL_5
#define HUMAN_SENSOR_CHAN_NAME WIFI_IOT_ADC_CHANNEL_3

#define AHT20_BAUDRATE 400*1000
#define AHT20_I2C_IDX WIFI_IOT_I2C_IDX_0


float humidity = 0.0f;      //AHT20测量的湿度
float temperature = 0.0f;   //AHT20测量的温度
extern uint8_t ywflag ;
extern uint8_t rtflag ;
extern uint8_t bcflag ;

//获取到的ADC值转换为电压值
static float ConvertToVoltage(unsigned short data)
{
    return (float)data * 1.8 * 4 / 4096;
}

static void EnvironmentTask(void *arg)
{
    (void)arg;
    uint32_t retval = 0;

    float gasSensorResistance = 0.0f;

    /*I2C IO口初始化化*/
    GpioInit();
    IoSetFunc(WIFI_IOT_IO_NAME_GPIO_13, WIFI_IOT_IO_FUNC_GPIO_13_I2C0_SDA);
    IoSetFunc(WIFI_IOT_IO_NAME_GPIO_14, WIFI_IOT_IO_FUNC_GPIO_14_I2C0_SCL);
    I2cInit(AHT20_I2C_IDX, AHT20_BAUDRATE);

    // 初始化AHT20
    uint8_t i=0;
    while (WIFI_IOT_SUCCESS != AHT20_Calibrate())
    {
        printf("AHT20 sensor init failed!\r\n");
        usleep(1000);
        i++;
        if(i>10)
            break;
    }
    
    //初始化Led灯
    Led_Init();
    //初始化蜂鸣器
    Beep_Init();

    while(1)
    {
        //AHT20开始测量
        retval = AHT20_StartMeasure();
        if (retval != WIFI_IOT_SUCCESS)
        {
            printf("trigger measure failed!\r\n");
        }

        //获取AHT20的测量结果，包括温度和湿度
        retval = AHT20_GetMeasureResult(&temperature, &humidity);
        if (retval != WIFI_IOT_SUCCESS)
        {
            printf("get humidity data failed!\r\n");
        }

        //烟雾（火灾）检测
        unsigned short data = 0;
        if (AdcRead(GAS_SENSOR_CHAN_NAME, &data, WIFI_IOT_ADC_EQU_MODEL_4, WIFI_IOT_ADC_CUR_BAIS_DEFAULT, 0)
                == WIFI_IOT_SUCCESS)
        {
            //数值转换
            float Vx = ConvertToVoltage(data);
            gasSensorResistance = 5 / Vx - 1;
            
            //检测到烟雾或者有毒气体
            if((gasSensorResistance < 2) && (ywflag ==0))
            {
                ywflag = 1;     //置位烟雾报警标志位
                Beep_Start();   //蜂鸣器发声报警
            }
            else if((gasSensorResistance >=2) && (ywflag ==1))     //恢复每检测到烟雾状态
            {
                ywflag = 0;         //复位标志位
                if(rtflag==0)       //没有防盗报警时
                    Beep_Stop();    //停止蜂鸣器发声
            }

        }

        //防盗检测
        unsigned short humandata = 0;
        if(bcflag)      //在布防状态下，防盗检测功能才开启
        {
            if (AdcRead(HUMAN_SENSOR_CHAN_NAME, &humandata, WIFI_IOT_ADC_EQU_MODEL_4, WIFI_IOT_ADC_CUR_BAIS_DEFAULT, 0)
                    == WIFI_IOT_SUCCESS)
            {
                //布防功能开启下，检测到人。
                //注意一旦触发防盗报警，就算恢复到没检测到人状态，也是会一直发声报警，只有切换到撤防状态，才能复位防盗报警标志位。
                if((humandata>1500)&&(rtflag==0))
                {
                    rtflag = 1;     //置位防盗报警标志位
                    Beep_Start();   //蜂鸣器发声报警
                }
            }
        }
        else
        {
            //切换到撤防状态，复位防盗报警标志位
            if((rtflag == 1) && (ywflag == 0))  //之前触发防盗报警，停止蜂鸣器发声。
                Beep_Stop();
            rtflag = 0;
        }

        sleep(1);
        Led_Set(GREEN,ON);      //系统心跳灯开
        sleep(1);
        Led_Set(GREEN,OFF);     //系统心跳灯关
    }
}

static void EnvironmentDemo(void)
{
    osThreadAttr_t attr;
    attr.name = "EnvironmentTask";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = 4096;
    attr.priority = osPriorityNormal;

    if (osThreadNew(EnvironmentTask, NULL, &attr) == NULL)
    {
        printf("[EnvironmentDemo] Falied to create EnvironmentTask!\n");
    }
}
APP_FEATURE_INIT(EnvironmentDemo);